Tack.Pane.Explorer = new Class({
	Extends: Tack.Pane,

	initialize: function (sidebar) {
		this.parent(sidebar, 'Explorer');

		var e = this, h = this.html, t = this.sidebar.tack;

		h.main.addClass('explorer');
		h.main.adopt(
			h.actions = new Element('ul', { 'class': 'actions' }).adopt(
				new Element('li', { 'class': 'save' }).adopt(
					new Element('a', {
						events: {
							click: function () {
								t.save();
								return false;
							}
						},
						href: '#',
						text: 'Save'
					})
				),
				new Element('li', { 'class': 'new-scene' }).adopt(
					new Element('a', {
						events: {
							click: function () {
								var name, scene, i = 1;
								while (t.game.scenes.has(name = 'Untitled Scene ' + i++));
								t.game.setScene(scene = new Tack.Scene(name));
								t.designer.setScene(scene);
								e.objectClicked.call(e, null, scene);
								return false;
							}
						},
						href: '#',
						text: 'New scene'
					})
				)
			),
			h.playLink = new Element('p', { 'class': 'play-link' }),
			h.objects = new Element('ol', { 'class': 'objects' })
		);
	},

	objectClicked: function (e, object) {
		this.sidebar.panes.each(function (pane) {
			if (pane instanceof Tack.Pane.Properties) {
				pane.setObject(object);
			}
		});
		
		return false;
	},

	refresh: function () {
		var t = this.sidebar.tack, d = t.designer, h = this.html;

		h.playLink.empty();
        if (t.game.id) {
            h.playLink.appendText('Play link: ');
            var a = new Element('a').inject(h.playLink);
            a.set('href', './play.html#' + t.game.id);
            a.set('text', a.href);
        }

		h.objects.empty();

		var addObject = (function (object, title, className) {
			var li = new Element('li', {
				events: {
					mouseenter: function () { this.addClass('hover'); },
					mouseleave: function () { this.removeClass('hover'); }
				},
				'class': className
			}).adopt(
				new Element('a', {
					events: {
						click: this.objectClicked.bindWithEvent(this, object),
						dblclick: function () {
							if (object instanceof Tack.Scene) {
								d.setScene(object);
							}
						}
					},
					href: '#',
					text: title
				})
			).store('object', object);

			h.objects.adopt(li);
		}).bind(this);
		
		addObject(t.game, t.game.title, 'game');
		
		var scenes = t.game.scenes.getKeys();
		scenes.sort();

		for (var i = 0; i < scenes.length; i++) {
			addObject(t.game.scenes[scenes[i]], scenes[i], 'scene');
		}
	}
});
